import { isNull } from "../Define";
import { IValue } from "../data/IValue";
import { IDataManager } from "../data/IDataManager";
/**
 * cgw20220527
 * 对本地存档的封装
 */
export default class LocalValue<T = any> implements IValue {



    protected value: T;

    private static keyMap: { [key: string]: string } = {}

    protected name: string = ''
    protected def: any;
    protected dataFlag: boolean = false;
    protected db: IDataManager = null;

    constructor(localStorage: IDataManager, name: string, def: any) {
        this.name = name;
        if (LocalValue.keyMap[name]) {
            console.error(' key has already exist')
        }
        LocalValue.keyMap[name] = name;
        this.setDefault(def)
        this.db = localStorage
        this.load();
    }

    clear() {
        this.setValue(this.copy())
    }
    
    load() {
        this.dataFlag = this.loadValue()
    }

    setDefault(def: any) {
        this.def = def;
    }

    copy() {
        return JSON.parse(JSON.stringify(this.def))
    }

    protected loadValue(): boolean {
        let save = this.db.getItem(this.name);
        if (!isNull(save)) {
            this.setSaveValue(JSON.parse(save), false)
            return true;
        } else {
            this.setSaveValue(this.copy(), false)
            return false;
        }

    }

    hasData(): boolean {
        return this.dataFlag;
    }

    save() {
        this.db.setItem(this.name, JSON.stringify(this.getSaveValue()))
    }

    getValue(): T {
        return this.value
    }


    setValue(value: T, isSave: boolean = true) {
        this.value = value;
        if (isSave) {
            this.save();
        }
    }

    protected getSaveValue(): any {
        return this.getValue()
    }

    protected setSaveValue(v: any, isSave: boolean = true) {
        this.setValue(v, isSave)
    }


    getInt() {
        return parseInt("" + this.getValue())
    }

    /**
     * 即将废弃 不再支持
     * @param n 
     * @param param 
     */
    updateValue(n: number, param?: any) {
        this.setSaveValue(this.getInt() + n)
    }


}